package com.cloud.shopping.listener;

import com.alibaba.fastjson.JSON;
import com.cloud.shopping.goods.model.Sku;
import com.cloud.shopping.page.feign.PageFeign;
import com.cloud.shopping.search.feign.SkuSearchFeign;
import com.cloud.shopping.search.model.SkuEs;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

import javax.annotation.Resource;

/**
 * @author John.zhang
 * @version Id: SkuHandler, v 1.0 2020/12/31 11:29 ZhiYong Exp $
 * 搜索数据同步
 * 静态页生成
 */

@CanalTable(value = "sku")
@Component
public class SkuHandler implements EntryHandler<Sku> {

    @Resource
    private SkuSearchFeign skuSearchFeign;

    @Resource
    private PageFeign pageFeign;

    /**
     * 增加数据监听
     *
     * @param sku sku
     */
    @SneakyThrows
    @Override
    public void insert(Sku sku) {
        if (sku.getStatus() == 1) {
            //将Sku转成JSON，再将JSON转成SkuEs
            skuSearchFeign.add(JSON.parseObject(JSON.toJSONString(sku), SkuEs.class));
        }
        html(sku);
    }

    /**
     * 修改数据监听
     *
     * @param before before
     * @param after  after
     */
    @SneakyThrows
    @Override
    public void update(Sku before, Sku after) {
        int status = 2;
        if (after.getStatus() == status) {
            //删除索引
            skuSearchFeign.delete(after.getId());
        } else {
            //更新
            skuSearchFeign.add(JSON.parseObject(JSON.toJSONString(after), SkuEs.class));
        }
        html(after);
    }

    /**
     * 删除数据监听
     *
     * @param sku sku
     */
    @Override
    public void delete(Sku sku) {
        skuSearchFeign.delete(sku.getId());
        html(sku);
    }


    private void html(Sku sku) {
        //生成静态页
        try {
            pageFeign.html(sku.getSpuId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
